<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <div style="text-align: left;display: inline-table;">
        <el-form-item>
          <el-input v-model="dataForm.key" placeholder="房间号/姓名/登记单号/交易流水号" clearable></el-input>
        </el-form-item>
        <el-form-item v-show="!shaixuan">
          <el-button @click="getDataList()">查询</el-button>
        </el-form-item>
      </div>
      <div style="text-align: right;display: inline-table;float: right;">
        <el-form-item label="">
          <el-button icon="el-icon-position" @click="startPay">支付</el-button>
          <!-- <el-button icon="el-icon-position" @click="viewYuShouQuanApi">预授权查询</el-button> -->
        </el-form-item>
        <el-form-item label="" v-if="isAuth('hotel:hotelseller:list')">
          <el-select multiple collapse-tags clearable style="width:180px;" v-model="sellerIds" filterable remote
            reserve-keyword @change="selectSeller" placeholder="商家名称" :remote-method="remoteMethod" :loading="loading">
            <el-option v-for="item in platformSeller" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="shaixuan = !shaixuan">高级搜索</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-collapse-transition>
      <div v-show="shaixuan">
        <el-form :model="dataForm" @keyup.enter.native="getDataList()" label-width="120px">
          <!--<el-form-item>
            <el-input v-model="dataForm.key" placeholder="流水号，账号，姓名" clearable></el-input>
          </el-form-item> -->
          <el-form-item label="操作员">
            <el-select placeholder="请选择操作员" v-model="dataForm.operator">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="item in userList" :key="item.userId" :label="item.username" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付平台">
            <el-select placeholder="请选择支付平台" v-model="searchParams.payType">
              <el-option v-for="item in payTypeList" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select placeholder="类型" v-model="dataForm.paySourceSign">
              <el-option label="全部" value=""></el-option>
              <el-option label="客房" value="0"></el-option>
              <el-option label="POS" value="1"></el-option>
              <!-- <el-option label="非住客帐" value="2"></el-option> -->
              <el-option label="其他" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="dataForm.state" placeholder="状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="预授权成功" value="1"></el-option>
              <el-option label="预授权完成" value="2"></el-option>
              <el-option label="全额退" value="3"></el-option>
              <el-option label="部分退" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-delete" @click="clearShaiXuan">清空筛选</el-button>
            <el-button type="primary" icon="el-icon-search" @click="getDataList()">{{ $t('Common.Query') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>


    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
      <!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
      <el-table-column prop="terminalTime" header-align="center" align="center" :formatter="dateFormat" label="交易时间"
        width="180">
      </el-table-column>

      <el-table-column prop="terminalTrace" header-align="center" align="center" label="收款单号" width="180"></el-table-column>


      <!-- 请求类型，010微信 020支付宝 -->
      <el-table-column prop="payType" header-align="center" align="center" label="支付">
        <template slot-scope="scope">
          <el-tag disable-transitions>{{ payTypeMap[scope.row.payType] }}</el-tag>
        </template>
      </el-table-column>


      <el-table-column prop="paySourceSign" header-align="center" align="center" label="类型">
        <template slot-scope="scope">
          <span v-if="scope.row.paySourceSign == 0">客房</span>
          <span v-if="scope.row.paySourceSign == 1">POS</span>
          <!-- <span v-if="scope.row.paySourceSign == 2">非住客帐</span> -->
          <span v-if="scope.row.paySourceSign == 3">其他</span>
        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="登记单号" width="150">
        <template slot-scope="scope">

          <template v-if="scope.row.paySourceSign == 0">
            <a type="text" v-if="scope.row.sysNo" @click="toAccounting({ singleId: scope.row.singleId }, '1')">{{ scope.row.sysNo }}</a>
            <span v-else> -- </span>
          </template>

          <template v-else-if="scope.row.paySourceSign == 1">
            <span v-if="scope.row.sysNoPos">{{ scope.row.sysNoPos }}</span>
            <span v-else> -- </span>
          </template>

          <template v-else>--</template>

        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="房间号">
        <template slot-scope="scope">

          <span v-if="scope.row.roomNum">{{ scope.row.roomSign }}{{ scope.row.roomNum }}</span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="姓名">
        <template slot-scope="scope">
          <span v-if="scope.row.name">{{ scope.row.name }}</span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column prop="totalFee" header-align="center" align="center" label="金额" :formatter="feeFormatter"></el-table-column>
      <el-table-column prop="refundFee" header-align="center" align="center" label="退款金额" :formatter="feeFormatter1"></el-table-column>
      <el-table-column prop="finishAmt" header-align="center" align="center" label="完成金额" :formatter="feeFormatter2"></el-table-column>
      <el-table-column prop="refundNo" header-align="center" align="center" label="退款单号" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.refundNo">{{scope.row.refundNo}}</span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column prop="outTradeNo" header-align="center" align="center" label="交易流水" width="260"></el-table-column>
      <el-table-column prop="operatorName" header-align="center" align="center" label="操作员" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.operatorName">{{scope.row.operatorName}}</span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <!--      <el-table-column header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <span v-if="scope.row.operatorName">{{scope.row.operatorName}}</span>
          <span v-else> -- </span>
        </template>
      </el-table-column> -->
      <el-table-column fixed="right" prop="resultCode" header-align="center" align="center" label="状态" width="136">

        <template slot-scope="scope">
          <el-tag :type="resStatusTagMap[scope.row.resultCode]" disable-transitions>{{ scope.row.returnMsg }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="state" header-align="center" align="center" label="类型" width="100">

        <template slot-scope="scope">
          <span v-if="scope.row.state == 1">已成功</span>
          <span v-if="scope.row.state == 2">已完成</span>
          <span v-if="scope.row.state == 3">全额退</span>
          <span v-if="scope.row.state == 4">部分退</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.state == 1" type="text" size="small" @click="preAuthFinishBtn(scope.row.id, scope.row)">预授权完成</el-button>
          <el-button v-if="scope.row.state == 1" type="text" size="small" @click="tuikuan(scope.row.id, scope.row)">退款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[1, 10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <ruzhang v-if="ruzhangVisible" ref="ruzhang" @refreshDataList="loadPage()"></ruzhang>
  </div>
</template>

<script>
  import AddOrUpdate from './thotelpreauthbarresult-add-or-update';
  import ruzhang from './ruzhang';
  import moment from 'moment';
  export default {
    data() {
      return {
        priceMap: {},
        currData: {},
        sellerIds: [],
        loading: false,
        platformSeller: [],
        shaixuan: false,
        dataForm: {
          key: '',
          operator: '',
          paySourceSign: '',
          state: ''
        },
        paySourceSigns: [],
        userList: [],
        dataList: [],
        withPage: [],
        peoples: [], //datalist对应人信息
        rooms: [], //对应房间信息
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        ruzhangVisible: false,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        resStatusTagMap: {
          '01': 'success',
          '02': 'danger',
          '03': 'info',
          '99': 'warning'
        },
        payTypeMap: {
          '010': '微信',
          '020': '支付宝',
          '1': '微信',
          '2': '支付宝'
        },
        payTypeList: [{
            id: '',
            value: '全部'
          },
          {
            id: '010',
            value: '微信'
          },
          {
            id: '020',
            value: '支付宝'
          },
          {
            id: '060',
            value: 'qq钱包'
          },
          {
            id: '080',
            value: '京东钱包'
          },
          {
            id: '090',
            value: '口碑'
          },
          {
            id: '100',
            value: '翼支付'
          },
          {
            id: '110',
            value: '银联二维码'
          }
        ],
        searchParams: {
          payType: ''
        }
      };
    },
    components: {
      AddOrUpdate,
      ruzhang,
    },
    activated() {
      //this.getDataList()
      this.init()
    },
    methods: {
      viewYuShouQuanApi() {
        this.$http({
          // url: this.$http.adornUrl('/hotel/thotelpreauthbarresult/preAuthFinish'),
          url: this.$http.adornUrl('/hotel/thotelpreauthbarresult/commonQuery'),
          method: 'post',
          data: this.$http.adornData({

          })
        }).then(({
          data
        }) => {
          if (data.code == 0) {
            this.$message({
              message: "F12控制台输出查看",
              type: "success",
              duration: 1500,
            });
            console.log("API报表接口：/hotel/thotelpreauthbarresult/commonQuery")
            console.log("预授权查询接口：", data)
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      toAccounting(item, type) {
        //将数据存储到本地
        var p = {
          singleId: item.singleId,
          type: type
        };
        this.$cookie.set('accounting', JSON.stringify(p));
        this.$router.push({
          name: 'accounting'
        });
      },
      startPay() {
        this.ruzhangVisible = true;
        this.$nextTick(() => {
          this.$refs.ruzhang.init();
        });
      },
      //清空筛选
      clearShaiXuan() {
        Object.assign(this.dataForm, this.$options.data().dataForm)
        this.getDataList();
      },
      init() {
        this.remoteMethod();
        this.$comReq.reqMerchantOperator()
          .then(({
            data
          }) => {
            this.userList = data.list
          });

        this.$nextTick(() => {
          this.loadPage();
        })
      },
      selectSeller(id, value) {
        this.getDataList()
      },
      //加载平台商家数据
      remoteMethod(query) {
        if (this.isAuth('hotel:hotelseller:list')) {
          this.loading = true;
          this.$http({
            url: this.$http.adornUrl("/hotel/hotelseller/platformSeller"),
            method: "get",
            params: this.$http.adornParams({
              sellerName: query
            })
          }).then(({
            data
          }) => {
            this.loading = false;
            if (data && data.code === 0) {
              this.platformSeller = data.page.list;
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      },
      preAuthFinishBtn(id, row) {
        this.$confirm('您确定要预授权完成吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl(`/hotel/thotelpreauthbarresult/view_ysq_finish_end/${row.id}`),
              method: 'get',
              params: this.$http.adornParams({})
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                });
                this.loadPage();
              } else {
                this.$message.error(data.msg);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
      },
      tuikuan(id, row) {
        this.$confirm('您确定要手工退款吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.openInputMoney(id, row);
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
      },
      openInputMoney(id, row) {
        this.$prompt('请输入退款金额,可退：' + (row.totalFee / 100).toFixed(2), '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            inputErrorMessage: '不可小于0',
            beforeClose: (action, instance, done) => {
              console.log(instance);
              if (action === 'confirm') {
                //判断金额
                if (parseFloat(row.totalFee / 100) < parseFloat(instance.inputValue)) {
                  this.$message({
                    type: 'info',
                    message: '退款金额不可超过可退金额'
                  });
                } else {
                  instance.confirmButtonLoading = true;
                  instance.confirmButtonText = '执行中...';
                  //请求
                  this.$http({
                    url: this.$http.adornUrl(`/hotel/thotelpreauthbarresult/view_ysq_finish/${row.id}`),
                    method: 'get',
                    params: this.$http.adornParams({
                      amount: instance.inputValue
                    })
                  }).then(({
                    data
                  }) => {
                    setTimeout(() => {
                      instance.confirmButtonLoading = false;
                      instance.confirmButtonText = '确定';
                    }, 300);
                    if (data && data.code === 0) {
                      done();
                    } else {
                      this.$message.error(data.msg);
                    }
                  });
                }
              } else {
                done();
              }
            }
          })
          .then(({
            value
          }) => {
            this.$message({
              type: 'success',
              message: '操作成功'
            });
            this.loadPage();
          })
          .catch(() => {});
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true;
        // this.$http({
        //   url: this.$http.adornUrl('/hotel/thotelpreauthbarresult/list'),
        //   method: 'get',
        //   params: this.$http.adornParams({
        //     'page': this.pageIndex,
        //     'limit': this.pageSize,
        //     'key': this.dataForm.key
        //   })
        // }).then(({ data }) => {
        //   if (data && data.code === 0) {
        //     this.dataList = data.page.list
        //     this.totalPage = data.page.totalCount
        //     this.peoples = data.peoples
        //     this.rooms = data.rooms
        //   } else {
        //     this.dataList = []
        //     this.totalPage = 0
        //   }
        //   this.dataListLoading = false
        // })
        this.loadPage();
      },
      loadPage() {
        var ids = ""
        if (this.sellerIds) {
          this.sellerIds.forEach((item, index) => {
            ids += item + ","
          })
          ids = ids.substring(0, ids.length - 1)
        }
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelpreauthbarresult/listWithPage'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            ids: ids,
            ...this.dataForm,
            payType: this.searchParams.payType
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataList = data.page.records;
            this.totalPage = data.page.total;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val;
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true;
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id);
        });
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] :
          this.dataListSelections.map(item => {
            return item.id;
          });
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/hotel/thotelpreauthbarresult/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        });
      },
      dateFormat(row, column) {
        return moment(moment(row.terminalTime, 'YYYYMMDDHHmmss')).format('YYYY-MM-DD HH:mm:ss');
      },
      feeFormatter(row, column) {
        return row.totalFee ? (row.totalFee / 100).toFixed(2) : '--';
      },
      feeFormatter1(row, column) {
        return row.refundFee ? (row.refundFee / 100).toFixed(2) : '--';
      },
      feeFormatter2(row, column) {
        return row.finishAmt ? (row.finishAmt / 100).toFixed(2) : '--';
      },
      GetDateTimeToString() {
        var date_ = new Date();
        var year = date_.getFullYear();
        var month = date_.getMonth() + 1;
        var day = date_.getDate();
        if (month < 10) month = '0' + month;
        if (day < 10) day = '0' + day;

        var hours = date_.getHours();
        var mins = date_.getMinutes();
        var secs = date_.getSeconds();
        var msecs = date_.getMilliseconds();
        if (hours < 10) hours = '0' + hours;
        if (mins < 10) mins = '0' + mins;
        if (secs < 10) secs = '0' + secs;
        if (msecs < 10) secs = '0' + msecs;
        return year + month + day + hours + mins + secs;
      },
      commonQuery(row) {
        let time = this.GetDateTimeToString();
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/commonQuery'),
          method: 'post',
          data: this.$http.adornData({
            pay_ver: '110', //版本号，当前版本110
            pay_type: row.payType, //000自动识别
            terminal_trace: row.terminalTrace, //终端流水号，填写商户系统的订单号
            terminal_time: time, //终端查询时间，yyyyMMddHHmmss，全局统一时间格式
            out_trade_no: row.outTradeNo
          })
        }).then(data => {
          console.log(data);
        });
      },
      preAuthFinish(row) {
        let time = this.GetDateTimeToString();
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/preAuthFinish'),
          method: 'post',
          data: this.$http.adornData({
            pay_ver: '110', //版本号，当前版本110
            terminal_trace: row.terminalTrace, //终端流水号，填写商户系统的订单号
            terminal_time: time, //终端查询时间，yyyyMMddHHmmss，全局统一时间格式
            finish_amt: '1', //完成金额
            out_trade_no: row.outTradeNo //单号
          })
        }).then(data => {
          console.log(data);
        });
      },
      preAuthCancel(row) {
        let time = this.GetDateTimeToString();
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/preAuthCancel'),
          method: 'post',
          data: this.$http.adornData({
            pay_ver: '110', //版本号，当前版本110
            terminal_trace: row.terminalTrace, //终端流水号，填写商户系统的订单号
            terminal_time: time, //终端查询时间，yyyyMMddHHmmss，全局统一时间格式
            out_trade_no: row.outTradeNo //单号
          })
        }).then(data => {
          console.log(data);
        });
      },
      preAuthQuery(row) {
        let time = this.GetDateTimeToString();
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/preAuthQuery'),
          method: 'post',
          data: this.$http.adornData({
            pay_ver: '110', //版本号，当前版本110
            terminal_trace: row.terminalTrace, //终端流水号，填写商户系统的订单号
            terminal_time: time, //终端查询时间，yyyyMMddHHmmss，全局统一时间格式
            out_trade_no: row.outTradeNo //单号
          })
        }).then(data => {
          console.log(data);
        });
      }
    }
  };
</script>
